# -*- coding: utf-8 -*-
# Version:python3.7
# Author:Jun
from odoo import api, models, tools

class Base(models.AbstractModel):
    _inherit = 'base'
    def get_copy_fields(self):
        '''
        获取所有的copy字段
        '''
        copy_fields = []
        records = self.env['ir.model.fields'].sudo().search([('model', '=', self._name), ('ttype', '=', 'one2many')])
        result_fields = [r.name for r in records if records]
        for field in result_fields:
            if not str(field).startswith('act') and not field.startswith('message_')  and not field.startswith('mail_'):
                copy_fields.append(field)
        return copy_fields

    def _is_type_value(self,data,relation_fields_type,field_name):
        field_type = relation_fields_type.get(field_name)
        expression = None
        if field_type=='integer':
           expression = data.get(field_name,0) > 0
        elif field_type=='float' or field_type=='monetary':
            expression = data.get(field_name,0) > 0
        elif field_type == 'char':
            expression = len(data.get(field_name,'').strip()) >0 if  data.get(field_name,'') else False
        return expression

    @api.model
    @tools.ormcache("copy_field")
    def get_relation_model_name(self,copy_field):
        """
        获取one2many类型的copy字段的模型
        """
        relation_model_name = self.fields_get(allfields=[copy_field]).get(copy_field).get('relation')
        return  relation_model_name

    @api.model
    # @tools.ormcache("copy_field","relation_fields")
    def get_relation_fields_type(self,copy_field,relation_fields):
        """
         copy_field 拷贝字段，
         relation_fields：dict类型，拷贝字段对应非空判断字段
        """

        relation_model_name = self.fields_get(allfields=[copy_field]).get(copy_field).get('relation')
        records = self.env['ir.model.fields'].sudo().search(
            [('model', '=', relation_model_name),('name','in',relation_fields), ('ttype', 'in', ['integer', 'float','char', 'monetary'])])
        result = {}
        for record in records:
            result.update({record.name:record.ttype})
        return  result

    def compute_creat_value(self, vals, check_datas):
        for check_data in check_datas:
            copy_field = check_data['fieldname']
            items = vals.get(copy_field, False)
            if items:
                new_items = []
                for item in items:
                    expression = True
                    for checkfieldline in check_data['checkfields']:
                        if expression is False:
                            break
                        if checkfieldline == []:
                            continue
                        expression = False
                        type_files = self.get_relation_fields_type(copy_field, checkfieldline)
                        for type_file in type_files:
                            relation_fields_type = self.get_relation_fields_type(copy_field, [type_file])
                            if self._is_type_value(item[2], relation_fields_type, type_file):
                                expression = True
                                break

                    if expression:
                        new_items.append(item)
                vals.update({copy_field: new_items})
        return vals

    def compute_write_value(self, vals, check_datas):
        for check_data in check_datas:
            copy_field = check_data['fieldname']
            items = vals.get(copy_field, False)
            if items:
                new_items = []
                for item in items:
                    if not isinstance(item[2], dict) and item[0] in [2,4]:
                        new_items.append(item)
                    if item[0] == 0:
                        expression = True
                        for checkfieldline in check_data['checkfields']:
                            if expression is False:
                                break
                            if checkfieldline == []:
                                continue
                            expression = False
                            type_files = self.get_relation_fields_type(copy_field, checkfieldline)
                            for type_file in type_files:
                                relation_fields_type = self.get_relation_fields_type(copy_field,[type_file])
                                if self._is_type_value(item[2], relation_fields_type, type_file):
                                    expression = True
                                    break
                        if expression:
                            new_items.append(item)
                    if item[0] == 1:
                        expression = True
                        data_info = False
                        for checkfieldline in check_data['checkfields']:
                            if expression is False:
                                break
                            if checkfieldline == []:
                                continue
                            expression = False
                            for checkfield in checkfieldline:
                                relation_fields_type = self.get_relation_fields_type(copy_field,[checkfield])
                                check_item = item.copy()
                                if checkfield not in check_item[2].keys():
                                    if data_info is False:
                                        data_info = self.env[self.get_relation_model_name(copy_field)].browse(check_item[1])
                                    check_item[2][checkfield] = data_info[checkfield]
                                if self._is_type_value(check_item[2], relation_fields_type, checkfield):
                                    expression = True
                                    break
                        if expression:
                            new_items.append(item)
                        else:
                            item_id = item[1]
                            data = item[2]
                            new_items.append([2, item_id, data])
                vals.update({copy_field: new_items})
        return vals
